package com.example.redis.demo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final String SECRET_KEY = "123456";

    private JwtUtil() {

    }


    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static Map<String, Object> parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * JWT生成token
     *
     * @param username
     * @param email
     * @param expiresInSeconds
     * @return
     */
    public static String generateToken(Long userId,
                                       String username, String email, Long expiresInSeconds) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", username);
        claims.put("id", userId);
        claims.put("email", email);
        claims.put("signDate", new Date(System.currentTimeMillis()));
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
//                .setExpiration(DateUtils.addSeconds(new Date(), expiresInSeconds.intValue()))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();

    }


}

